writeLines("************************************************************************************************************************")
writeLines("************************************************************************************************************************")

# 	Filename: summarystats_source.R
# 	For: Barry Hashimoto, "Autocratic Consent to International Law: the Case of the International Criminal Court's Jurisdiction," International Organization.
# 	Description: Code to produce summary statistics of imputed and unimputed data sets shown in the supplementary appendix.
# 	Author: Barry Hashimoto
# 	Date: August 2019
   
  timestamp()
  options(scipen=999) # Prevent scientific formatting of numbers.
  rm(list = ls())
  load("imputedicc.RData")
  
  suppressPackageStartupMessages({library(foreign); library(data.table); library(caret)
  library(Amelia); library(mitools); library(lattice); library(xtable)
  library(doBy); library(mvtnorm); library(plyr); 
  library(psych); library(car); library(hexbin); library(lattice)})

  # Rename certain variables so that code from an earlier version of this files can remain unmodified.
   for (z in 1:10){full$imputations[[z]]$ruleoflaw <- full$imputations[[z]]$vdem.ruleoflaw}

####################################################################
# Row-bind imputed observations from all ten data sets in order to calculate summary statistics on them.

  appended <- rbind(full$imputations[[1]],full$imputations[[2]],full$imputations[[3]],
				  full$imputations[[4]],full$imputations[[5]],full$imputations[[6]],
				  full$imputations[[7]],full$imputations[[8]],full$imputations[[9]],full$imputations[[10]])

  appended <- appended[appended$quarter>=154,]

  attach(appended)

########################################################################
writeLines(""); writeLines("") 
writeLines("----------------------------------------------------------------------------------------------------------------------")
 writeLines("# Print summary statistics of the 10 imputed data sets.") 

  stats <- function(x){ 
	mat <- cbind(sapply(x, min, na.rm=TRUE), sapply(x, function(x) {quantile(x, .33, na.rm=TRUE)}), 
	sapply(x, function(x) {quantile(x, .5, na.rm=TRUE)}), sapply(x, mean, na.rm=TRUE), 
	sapply(x, function(x) {quantile(x, .67, na.rm=TRUE)}), sapply(x, max, na.rm=TRUE), 
	sapply(x, sd, na.rm=TRUE), sapply(x, mad, na.rm=TRUE))
	colnames(mat) <- c("Min", "33rd  %-ile", "Median", "Mean", "67th %-ile", "Max", "SD", "MAD")
	return(mat)
	}

  vars <- data.frame(ratifyrome, leaderexitsoffice, logdeaths, demaid.scaled, multilataid.scaled, dod.scaled, 
    capital.scaled, RomeStatuteRatification, gdp.scaled, democracy, ruleoflaw, civil, common, mixed, islam, pre98conflict, 
    medianIMR, ptssum.mean, x.ucdp.incidence, cowwar, logoilrent, loggrowth, logpop, logrefugees, logsoldierspercent, logexpmil, 
    maleunemp, allunemp, eth, rel, rug, quartersinoffice, quartersinoffice.since1998Q3)
	
  varnames <- c("Leader ratifies", "Leader exits office", "Battle deaths", "DAC-EC aid", "Multilateral aid", "Multilateral loans", 
    "Total aid and loans", "ICC jurisdiction", "GDP", "Democracy", "Rule of law", "Civil law", "Common law", "Mixed law", "Islamic law", 
    "Prior conflict", "Prior infant mortality", "Prior repression", "Civil conflict", "Interstate war", "Oil rents", "GDP growth", 
    "Population", "Refugees", "Military personnel", "Military expenditures",  "Male youth unemployment", "Unemployment", "Ethnic polarization", 
    "Religious polarization", "Ruggedness",  "Quarters of incumbency", "Quarters of incumbency since 1998-Q3")

stats.table <- stats(vars)
table <- xtable(stats.table, digits=2)
rownames(table) <- varnames
print(table)

writeLines(""); writeLines("") 
writeLines("# How many leaders and states in 1998 Q3 - 2017 Q4?")
print(length(unique(full$imputations[[z]]$lcode)))
print(length(unique(full$imputations[[z]]$ccode)))
#print(length(unique(full$imputations[[z]]$year)))

########################################################################
writeLines(""); writeLines("") 
writeLines("----------------------------------------------------------------------------------------------------------------------")
 writeLines("# Print summary statistics of the unimputed data set.") 
 
 
detach(appended) 

rm(list = ls())
setwd("/Users/barryhashimoto/Desktop/HashimotoReplicationFile2019")
load("iccdata.Rdata")

# Calculate the number of states that had accepted J by 2017 and were autocracies in 98-17. We have 121 b/c Palestine and San Marino are not in data set.
  all <- data.table(all)
  w <- unique(all[RomeStatuteRatification==1 & year==2017, ccode])

# Calculate percent of time autocratic by country. Get the mean of democracy by country.
  short <- all[ifelse(all$ccode %in% w, 1, 0) == 1, ]
  library(doBy)
  pmean <- function(x){mean(x, na.rm = T)}
  short <- summaryBy(x.ucdp.incidence + democracy ~ ccode, data = short, FUN=c(pmean)) #Calculate 1988-1998 mean by state.
  length(unique(short$ccode[short$x.ucdp.incidence.pmean>0])) # 34 states had a civil conflict in this period. 34/121. 28%. Same if add Pal & SM.
  length(unique(short$ccode[short$democracy.pmean<1])) #44% were closed or electoral autocracies part of the time. 53/121. 44%. Same if add Pal & SM.
 
# Rename certain variables so that code from an earlier version of this files can remain unmodified.
   all$ruleoflaw <- all$vdem.ruleoflaw

# Legal tradition dummies.
  legaldummies <- as.data.frame(predict(dummyVars(~ as.factor(legaltrad2), data = all), 
  	newdata = all))
  names(legaldummies) <- c("civil", "common", "mixed", "islam")
  all <- data.frame(all, legaldummies)

# Identify the OECD DAC States so they can be dropped
  dacmemberlist <- c("Australia", "Austria", "Belgium", "Canada", "Denmark", "Finland", "France", "Germany", 
    "Greece", "Ireland", "Italy", "Japan", "South Korea", "Luxembourg", "Netherlands", "New Zealand", "Norway", 
    "Portugal", "Spain", "Sweden", "Switzerland", "United Kingdom", "United States of America")
    
# Exclude DAC member states
  all <- all[ifelse(all$country %in% dacmemberlist, 1, 0)==0,]
  
# Drop all observations before 1998(3), corresponding to quarter number 154.
  all <- all[all$quarter>=154, ]

########################################################################
# A function to get desired summary statistics.
stats <- function(x){ 
	mat <- cbind(sapply(x, min, na.rm=TRUE), sapply(x, function(x) {quantile(x, .33, na.rm=TRUE)}), 
	sapply(x, function(x) {quantile(x, .5, na.rm=TRUE)}), sapply(x, mean, na.rm=TRUE), 
	sapply(x, function(x) {quantile(x, .67, na.rm=TRUE)}), sapply(x, max, na.rm=TRUE), 
	sapply(x, sd, na.rm=TRUE), sapply(x, mad, na.rm=TRUE))
	colnames(mat) <- c("Min", "33rd  %-ile", "Median", "Mean", "67th %-ile", "Max", "SD", "MAD")
	return(mat)
	}

attach(all)

 vars <- data.frame(ratifyrome, leaderexitsoffice, logdeaths, demaid.scaled, multilataid.scaled, dod.scaled, capital.scaled, 
	RomeStatuteRatification, gdp.scaled, democracy, ruleoflaw, civil, common, mixed, islam, pre98conflict, medianIMR, ptssum.mean, 
	x.ucdp.incidence, cowwar, logoilrent, loggrowth, logpop, logrefugees, logsoldierspercent, logexpmil, maleunemp, allunemp, 
	eth, rel, rug, quartersinoffice, quartersinoffice.since1998Q3)
	
 varnames <- c("Leader ratifies", "Leader exits office", "Battle deaths", "DAC-EC aid", "Multilateral aid", "Multilateral loans", 
 	"Total aid and loans", "ICC jurisdiction", "GDP", "Democracy", "Rule of law", "Civil law", "Common law", "Mixed law", "Islamic law", 
	 "Prior conflict", "Prior infant mortality", "Prior repression", "Civil conflict", "Interstate war", "Oil rents", "GDP growth", "Population", 
	 "Refugees", "Military personnel", "Military expenditures",  "Male youth unemployment", "Unemployment", "Ethnic polarization", "Religious polarization", 
	 "Ruggedness",  "Quarters of incumbency", "Quarters of incumbency since 1998-Q3")

  stats.table <- stats(vars)
  table <- xtable(stats.table, digits=2)
  rownames(table) <- varnames
  print(table)

#writeLines("# How many leaders and states in 1998 Q3 - 2017 Q4 are *completely observed* on all variables used in analysis models?")
  
    complete <- data.frame(ccode, lcode, year, leaderexitsoffice, logdeaths, demaid.scaled, multilataid.scaled, dod.scaled, capital.scaled, 
    RomeStatuteRatification, gdp.scaled, democracy, ruleoflaw, civil, common, mixed, islam, pre98conflict, medianIMR, ptssum.mean, x.ucdp.incidence, 
    cowwar, logoilrent, loggrowth, logpop, logrefugees, logsoldierspercent, logexpmil, maleunemp, allunemp, eth, rel, rug, quartersinoffice, 
    quartersinoffice.since1998Q3)
  complete <- complete[complete.cases(complete),]
  length(unique(complete$lcode))
  length(unique(complete$ccode))
  length(unique(complete$year))
  
########################################################################
# End
